<template>
    <div class="student-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" inline label-width="100px">
                <el-form-item label="姓名">
                    <el-input v-model="searchForm.sname" placeholder="请输入姓名"/>
                </el-form-item>
                <el-form-item label="QQ">
                    <el-input v-model="searchForm.qq" placeholder="请输入QQ号"/>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="searchForm.telephone" placeholder="请输入电话号码"/>
                </el-form-item>
                <el-form-item label="入学日期">
                    <el-date-picker
                            v-model="searchForm.enterdateStart"
                            format="YYYY-MM-DD"
                            placeholder="开始日期"
                            type="date"
                            value-format="YYYY-MM-DD"
                    />
                    <span style="margin: 0 10px">-</span>
                    <el-date-picker
                            v-model="searchForm.enterdateEnd"
                            format="YYYY-MM-DD"
                            placeholder="结束日期"
                            type="date"
                            value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格工具栏 -->
        <div class="toolbar">
            <el-button type="primary" @click="handleAdd">新增学生</el-button>
        </div>

        <!-- 学生表格 -->
        <el-table
                v-loading="loading"
                :data="tableData"
                border
                stripe
                style="width: 100%"
        >
            <el-table-column label="学号" prop="stuno" width="100"/>
            <el-table-column label="姓名" prop="sname" width="120"/>
            <el-table-column label="性别" prop="sex" width="80"/>
            <el-table-column label="QQ" prop="qq" width="120"/>
            <el-table-column label="微信" prop="wechat" width="120"/>
            <el-table-column label="地址" prop="address" show-overflow-tooltip/>
            <el-table-column label="来自城市" prop="fromcity" width="120"/>
            <el-table-column label="电话" prop="telephone" width="120"/>
            <el-table-column label="邮箱" prop="email" width="150"/>
            <!--            <el-table-column label="年级ID" prop="gradeid" width="100"/>-->
            <el-table-column label="年级名称" prop="gname" width="120"/>

            <!-- 身份证图片列 -->
            <el-table-column label="身份证" width="120">
                <template #default="{ row }">
                    <!--                    ## {{ getFullIdCardPath(row.idcard) }}$$$-->
                    <el-image
                            v-if="row.idcard"
                            :initial-index="0"
                            :preview-src-list="[getFullIdCardPath(row.idcard)]"
                            :src="getFullIdCardPath(row.idcard)"
                            class="idcard-image"
                            fit="cover"
                            style="width: 50px; height: 50px"
                    />
                    <span v-else>无图片</span>
                </template>
            </el-table-column>

            <!-- 生日和入学日期 -->
            <el-table-column label="生日" prop="birthday" width="120">
                <template #default="{ row }">
                    {{ formatDate(row.birthday) }}
                </template>
            </el-table-column>
            <el-table-column label="入学日期" prop="enterdate" width="120">
                <template #default="{ row }">
                    {{ formatDate(row.enterdate) }}
                </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column fixed="right" label="操作" width="150">
                <template #default="{ row }">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>

                    <el-button size="small" @click="handleQueryScore(row)">查看成绩</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                class="pagination"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />

        <!-- 编辑/新增对话框 -->
        <el-dialog
                v-model="dialogVisible"
                :title="dialogTitle"
                width="500px"
                @close="handleDialogClose"
        >
            <el-form
                    ref="formRef"
                    :model="form"
                    :rules="rules"
                    label-width="100px"
            >
                <el-form-item label="姓名" prop="sname">
                    <el-input v-model="form.sname"/>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="form.sex" placeholder="请选择性别">
                        <el-option label="男" value="男"/>
                        <el-option label="女" value="女"/>
                        <el-option label="妖" value="妖"/>
                        <el-option label="人妖" value="人妖"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="QQ" prop="qq">
                    <el-input v-model="form.qq"/>
                </el-form-item>
                <el-form-item label="微信" prop="wechat">
                    <el-input v-model="form.wechat"/>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="form.address"/>
                </el-form-item>
                <el-form-item label="来自城市" prop="fromcity">
                    <el-input v-model="form.fromcity"/>
                </el-form-item>
                <el-form-item label="电话" prop="telephone">
                    <el-input v-model="form.telephone"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email"/>
                </el-form-item>
                <el-form-item label="密码" prop="pass">
                    <el-input v-model="form.pass" type="password"/>
                </el-form-item>

                <!-- 年级选择下拉框，支持分页 -->
                <el-form-item label="年级" prop="gradeid">
                    <el-select
                            v-model="form.gradeid"
                            :loading="gradeLoading"
                            :remote-method="searchGrades"
                            filterable
                            placeholder="请选择年级"
                            remote
                            @focus="loadGrades"
                    >
                        <el-option
                                v-for="item in gradeOptions"
                                :key="item.id"
                                :label="item.gname"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="生日" prop="birthday">
                    <el-date-picker
                            v-model="form.birthday"
                            format="YYYY-MM-DD"
                            placeholder="请选择生日"
                            style="width: 100%"
                            type="date"
                            value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item label="入学日期" prop="enterdate">
                    <el-date-picker
                            v-model="form.enterdate"
                            format="YYYY-MM-DD"
                            placeholder="请选择入学日期"
                            style="width: 100%"
                            type="date"
                            value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item label="身份证图片" prop="idcard">
                    <el-upload
                            :action="uploadUrl"
                            :before-upload="beforeIdCardUpload"
                            :on-success="handleIdCardSuccess"
                            :show-file-list="false"
                            class="idcard-uploader"
                    >
                        <img v-if="form.idcard" :src="getFullIdCardPath(form.idcard)" class="idcard-preview"/>
                        <el-icon v-else class="idcard-uploader-icon">
                            <Plus/>
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {ref, reactive, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {useRouter} from 'vue-router'
import {
    paging,
    getStudent,
    addStudent,
    updateStudent,
    deleteStudent,
    uploadIdCard
} from '@/apis/student'
import {paging as pagingGrades} from '@/apis/grade'

export default {
    name: 'Student',
    components: {
        Plus
    },
    setup() {
        // 加载状态
        const loading = ref(false)
        const gradeLoading = ref(false)

        // 表格数据
        const tableData = ref([])
        //router
        const router = useRouter();
        // 搜索表单
        const searchForm = reactive({
            sname: '',
            qq: '',
            telephone: '',
            enterdateStart: '',
            enterdateEnd: ''
        })

        // 分页
        const pagination = reactive({
            currentPage: 1,
            pageSize: 10,
            total: 0
        })

        // 对话框
        const dialogVisible = ref(false)
        const dialogTitle = ref('')
        const isEdit = ref(false)

        // 表单引用
        const formRef = ref(null)

        // 年级选项
        const gradeOptions = ref([])

        // 表单数据
        const form = reactive({
            stuno: 0,
            sname: '',
            sex: '男',
            qq: '',
            wechat: '',
            address: '',
            fromcity: '',
            telephone: '',
            email: '',
            pass: '',
            gradeid: null,
            birthday: '',
            enterdate: '',
            idcard: '',
            gname: ''
        })

        // 表单验证规则
        const rules = {
            sname: [
                {required: true, message: '请输入姓名', trigger: 'blur'},
                {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
            ],
            sex: [{required: true, message: '请选择性别', trigger: 'change'}],
            qq: [
                {pattern: /^\d{5,15}$/, message: 'QQ号格式不正确', trigger: 'blur'}
            ],
            telephone: [
                {pattern: /^\d{5,16}$/, message: '电话号码格式不正确', trigger: 'blur'}
            ],
            pass: [
                {required: true, message: '请输入密码', trigger: 'blur'},
                {min: 5, message: '密码至少5位', trigger: 'blur'}
            ],
            email: [
                {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
            ],
            gradeid: [
                {required: true, message: '请选择年级', trigger: 'change'}
            ],
            birthday: [{required: true, message: '请选择生日', trigger: 'change'}],
            enterdate: [{required: true, message: '请选择入学日期', trigger: 'change'}]
        }

        // 上传URL:${import.meta.env.VITE_BASE_API}
        const uploadUrl = `/api/student/upload/idcard`

        // 格式化日期
        const formatDate = (dateString) => {
            if (!dateString) return ''
            const date = new Date(dateString)
            return date.getFullYear() + '-' +
                String(date.getMonth() + 1).padStart(2, '0') + '-' +
                String(date.getDate()).padStart(2, '0')
        }

        // 获取完整的身份证图片路径
        const getFullIdCardPath = (idcardPath) => {
            // 如果路径已经包含uploads或http，则直接返回
            if (!idcardPath) return ''
            if (idcardPath.startsWith('http') || idcardPath.startsWith('uploads/')) {
                return idcardPath
            }
            // 否则添加uploads前缀
            return `api/uploads/${idcardPath}`
        }

        // 加载年级数据
        const loadGrades = async (pageNum = 1, pageSize = 20) => {
            gradeLoading.value = true
            try {
                const res = await pagingGrades({pageNo: pageNum, pageSize: pageSize})
                gradeOptions.value = res.data.records
            } catch (err) {
                ElMessage.error('获取年级数据失败')
            } finally {
                gradeLoading.value = false
            }
        }

        // 搜索年级
        const searchGrades = async (query) => {
            if (query !== '') {
                gradeLoading.value = true
                try {
                    const res = await pagingGrades({pageNo: 1, pageSize: 20, gname: query})
                    gradeOptions.value = res.data.records
                } catch (err) {
                    ElMessage.error('搜索年级失败')
                } finally {
                    gradeLoading.value = false
                }
            } else {
                loadGrades()
            }
        }

        // 获取表格数据
        const fetchData = async () => {
            loading.value = true
            try {
                const params = {
                    pageNum: pagination.currentPage,
                    pageSize: pagination.pageSize,
                    ...searchForm
                }

                const res = await paging(params)
                tableData.value = res.data.records
                pagination.total = res.data.total
            } catch (err) {
                ElMessage.error('获取数据失败')
            } finally {
                loading.value = false
            }
        }

        // 处理搜索
        const handleSearch = () => {
            pagination.currentPage = 1
            fetchData()
        }

        // 重置搜索
        const resetSearch = () => {
            Object.assign(searchForm, {
                sname: '',
                qq: '',
                telephone: '',
                enterdateStart: '',
                enterdateEnd: ''
            })
            pagination.currentPage = 1
            fetchData()
        }

        // 处理分页大小变化
        const handleSizeChange = (val) => {
            pagination.pageSize = val
            pagination.currentPage = 1
            fetchData()
        }

        // 处理当前页变化
        const handleCurrentChange = (val) => {
            pagination.currentPage = val
            fetchData()
        }

        // 处理新增
        const handleAdd = () => {
            dialogTitle.value = '新增学生'
            isEdit.value = false
            resetForm()
            // 加载年级数据
            loadGrades()
            dialogVisible.value = true
        }
        //查看成绩
        const handleQueryScore = (row) => {
            // 构造带参数的URL
            const routeData = router.resolve({
                path: '/exam2/' + row.stuno
            });
            window.open(routeData.href, '_blank');
        }

        // 处理编辑
        const handleEdit = async (row) => {
            dialogTitle.value = '编辑学生'
            isEdit.value = true

            // 获取学生详情
            try {
                const res = await getStudent(row.stuno)
                Object.assign(form, res.data)
                //form.qq = res.data.qq
                //form.wechat = res.data.wechat
            } catch (err) {
                ElMessage.error('获取学生信息失败')
                return
            }

            // 加载年级数据
            loadGrades()

            dialogVisible.value = true
        }

        // 处理删除
        const handleDelete = (row) => {
            ElMessageBox.confirm(
                `确定要删除学生 ${row.sname} 吗？`,
                '确认删除',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(async () => {
                try {
                    await deleteStudent(row.stuno)
                    ElMessage.success('删除成功')
                    fetchData()
                } catch (err) {
                    ElMessage.error('删除失败')
                }
            }).catch(() => {
                // 用户取消删除
            })
        }

        // 重置表单
        const resetForm = () => {
            Object.assign(form, {
                stuno: 0,
                sname: '',
                sex: '',
                qq: '',
                wechat: '',
                address: '',
                fromcity: '',
                telephone: '',
                email: '',
                pass: '',
                gradeid: null,
                birthday: '',
                enterdate: '',
                idcard: '',
                gname: ''
            })
        }

        // 处理对话框关闭
        const handleDialogClose = () => {
            formRef.value?.resetFields()
        }

        // 提交表单
        const submitForm = () => {
            formRef.value?.validate(async (valid) => {
                if (!valid) return

                try {
                    if (isEdit.value) {
                        await updateStudent(form.stuno, form)
                        ElMessage.success('更新成功')
                    } else {
                        await addStudent(form)
                        ElMessage.success('添加成功')
                    }

                    dialogVisible.value = false
                    fetchData()
                } catch (err) {
                    ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
                }
            })
        }

        // 处理身份证上传成功
        const handleIdCardSuccess = (response) => {
            if (response.code === 200) {
                form.idcard = response.data
                ElMessage.success('上传成功')
            } else {
                ElMessage.error('上传失败')
            }
        }

        // 上传前检查
        const beforeIdCardUpload = (file) => {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 10

            if (!isJPG) {
                ElMessage.error('身份证图片只能是 JPG 或 PNG 格式!')
            }
            if (!isLt2M) {
                ElMessage.error('身份证图片大小不能超过 10MB!')
            }

            return isJPG && isLt2M
        }

        // 初始化数据
        onMounted(() => {
            fetchData()
        })

        return {
            loading,
            gradeLoading,
            tableData,
            searchForm,
            pagination,
            dialogVisible,
            dialogTitle,
            isEdit,
            formRef,
            form,
            rules,
            uploadUrl,
            gradeOptions,

            formatDate,
            getFullIdCardPath,
            loadGrades,
            searchGrades,
            handleSearch,
            resetSearch,
            handleSizeChange,
            handleCurrentChange,
            handleAdd,
            handleEdit,
            handleQueryScore,
            handleDelete,
            handleDialogClose,
            submitForm,
            handleIdCardSuccess,
            beforeIdCardUpload
        }
    }
}
</script>

<style scoped>
.student-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.toolbar {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.idcard-image {
    cursor: pointer;
    transition: transform 0.3s;
}

.idcard-image:hover {
    transform: scale(2);
    z-index: 999;
}

.idcard-uploader .idcard-preview {
    width: 100%;
    height: 178px;
    display: block;
}

.idcard-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.idcard-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.idcard-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
}
</style>